package com.example.baselibrary.utlis

import android.app.Application
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong

/**
 * 高性能全局计时器 - 兼容API 21优化版
 *
 * 主要特点：
 * 1. 兼容Android 5.0 (API 21)及以上版本
 * 2. 使用弱引用防止内存泄漏
 * 3. 精确计时与事件触发
 * 4. 线程安全集合操作
 * 5. 生命周期感知
 * 6. 性能监控与优化
 * 这段Kotlin代码实现了一个高性能、线程安全且生命周期感知的全局计时器。主要功能包括：
 * 精确计时：基于SystemClock.elapsedRealtime()提供毫秒级计时。
 * 事件通知：每秒和每分钟触发回调，支持注册/注销监听器。
 * 性能优化：
 * 使用WeakReference防止内存泄漏；
 * 动态调整定时器频率（前台高精度，后台低频率）；
 * 性能监控与日志记录。
 * 生命周期感知：通过LifecycleObserver自动适配应用前后台切换。
 *
 * @author 郑
 * @date 2025/7/30.
 */
object GlobalTimer : LifecycleObserver {

    // 原子状态变量
    private val startTime = AtomicLong(0)
    private val isTimerRunning = AtomicBoolean(false)
    private val lastMinuteMark = AtomicLong(-1)

    // 使用兼容API 21的并发集合
    private val listeners = Collections.newSetFromMap(
        ConcurrentHashMap<TimerListener, Boolean>()
    )

    // Handler相关
    private var handler: Handler? = null
    private var runnable: Runnable? = null

    // 后台状态跟踪
    @Volatile private var isAppInForeground = true

    // 性能监控
    private var notificationCount = 0L
    private var maxNotificationTime = 0L
    private var totalNotificationTime = 0L

    // 初始化应用生命周期监听
    fun init(application: Application) {
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    // 应用进入前台
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        isAppInForeground = true
        adjustTimerPrecision()
    }

    // 应用进入后台
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        isAppInForeground = false
        adjustTimerPrecision()
    }

    // 启动计时器
    fun start() {
        if (isTimerRunning.getAndSet(true)) return

        startTime.set(SystemClock.elapsedRealtime())
        lastMinuteMark.set(-1)
        handler = Handler(Looper.getMainLooper())

        runnable = object : Runnable {
            override fun run() {
                if (!isTimerRunning.get()) return

                val currentElapsed = SystemClock.elapsedRealtime() - startTime.get()
                notifyListeners(currentElapsed)

                val delay = calculateOptimalDelay(currentElapsed)
                val nextTime = SystemClock.uptimeMillis() + delay
                handler?.postAtTime(this, nextTime)
            }
        }

        handler?.post(runnable!!)
    }

    // 停止计时器
    fun stop() {
        if (!isTimerRunning.getAndSet(false)) return

        handler?.removeCallbacksAndMessages(null)
        handler = null
        runnable = null
        listeners.clear()

        logPerformanceStats()
    }

    // 注册监听器
    fun registerListener(listener: TimerListener) {
        synchronized(listeners) {
            listeners.add(listener)
            cleanupDeadListeners()
        }
    }

    // 注销监听器
    fun unregisterListener(listener: TimerListener) {
        synchronized(listeners) {
            listeners.remove(listener)
            cleanupDeadListeners()
        }
    }

    // 获取当前时间（毫秒）
    fun getElapsedTime(): Long {
        return if (isTimerRunning.get()) {
            SystemClock.elapsedRealtime() - startTime.get()
        } else {
            0
        }
    }

    // 打印性能统计数据
    fun logPerformanceStats() {
        if (notificationCount > 0) {
            val avgTime = totalNotificationTime / notificationCount
            Log.d("GlobalTimer", "Performance Stats: " +
                    "Notifications=$notificationCount, " +
                    "MaxTime=${maxNotificationTime}μs, " +
                    "AvgTime=${avgTime}μs")
        }
    }

    // 通知所有监听器（核心优化）
    private fun notifyListeners(currentElapsed: Long) {
        val startTime = System.nanoTime()
        val currentMinute = currentElapsed / 60000

        // 原子性检查并更新分钟标记
        val lastMinute = lastMinuteMark.get()
        val minuteChanged = currentMinute > lastMinute

        if (minuteChanged && lastMinuteMark.compareAndSet(lastMinute, currentMinute)) {
            notifyMinuteEvents(currentMinute)
        }

        notifySecondEvents(currentElapsed)

        // 记录性能数据
        recordPerformance(startTime)
    }

    // 通知秒级事件
    private fun notifySecondEvents(currentElapsed: Long) {
        synchronized(listeners) {
            val iterator = listeners.iterator()
            while (iterator.hasNext()) {
                val listener = iterator.next()
                try {
                    listener.onSecondElapsed(currentElapsed)
                } catch (e: Exception) {
                    Log.w("GlobalTimer", "Listener error in onSecondElapsed", e)
                    iterator.remove()
                }
            }
        }
    }

    // 通知分钟事件
    private fun notifyMinuteEvents(currentMinute: Long) {
        synchronized(listeners) {
            val iterator = listeners.iterator()
            while (iterator.hasNext()) {
                val listener = iterator.next()
                try {
                    listener.onMinuteElapsed(currentMinute)
                } catch (e: Exception) {
                    Log.w("GlobalTimer", "Listener error in onMinuteElapsed", e)
                    iterator.remove()
                }
            }
        }
    }

    // 记录性能指标
    private fun recordPerformance(startTime: Long) {
        val elapsed = (System.nanoTime() - startTime) / 1000 // 转换为微秒
        notificationCount++
        totalNotificationTime += elapsed
        if (elapsed > maxNotificationTime) maxNotificationTime = elapsed

        // 超过阈值时警告
        if (elapsed > 1000) {
            Log.w("GlobalTimer", "Notification took ${elapsed}μs (${listeners.size} listeners)")
        }
    }

    // 智能计算下次延迟
    private fun calculateOptimalDelay(currentElapsed: Long): Long {
        return when {
            // 后台模式使用较低频率
            !isAppInForeground -> 5000L

            // 接近分钟点时提高频率
            currentElapsed % 60000 < 1000 -> 200L

            // 其他情况精确对齐秒边界
            else -> 1000 - (currentElapsed % 1000)
        }
    }

    // 调整计时精度
    private fun adjustTimerPrecision() {
        handler?.removeCallbacksAndMessages(null)
        handler?.post(runnable ?: return)
    }

    // 清理无效监听器
    private fun cleanupDeadListeners() {
        synchronized(listeners) {
            val iterator = listeners.iterator()
            while (iterator.hasNext()) {
                val listener = iterator.next()
                if (listener is WeakTimerListener && !listener.isAlive()) {
                    iterator.remove()
                }
            }
        }
    }
}

// 计时器监听接口
/**
 * 定时器监听器接口，用于监听时间流逝事件
 */
interface TimerListener {
    /**
     * 当一秒流逝时调用此方法
     * @param millis 已流逝的毫秒数
     */
    fun onSecondElapsed(millis: Long)

    /**
     * 当一分钟流逝时调用此方法
     * @param minutes 已流逝的分钟数
     */
    fun onMinuteElapsed(minutes: Long)
}


// 弱引用监听器包装器
class WeakTimerListener(delegate: TimerListener) : TimerListener {
    private val weakRef = WeakReference(delegate)

    override fun onSecondElapsed(millis: Long) {
        weakRef.get()?.onSecondElapsed(millis)
    }

    override fun onMinuteElapsed(minutes: Long) {
        weakRef.get()?.onMinuteElapsed(minutes)
    }

    fun isAlive(): Boolean = weakRef.get() != null
}